import { Global, Logger, Module } from '@nestjs/common'
import { AppController } from './app.controller'
import { AppService } from './app.service'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { UserModule } from './user/user.module'
// import LoadConfiguration from './configuration'
import * as Joi from 'joi'
import * as dotenv from 'dotenv'
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm'
import { ConfigEnum } from './enum/config.enum'
import { User } from './user/user.entity'
import { Profile } from './user/profile.entity'
import { Roles } from './roles/roles.entity'
import { Logs } from './logs/logs.entity'

const envFilePath = `.env.${process.env.NODE_ENV || 'development'}`

@Global() // 全局模块
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath,
      load: [() => dotenv.config({ path: '.env' })],
      // load: [LoadConfiguration],
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test')
          .default('development'),
        DB_PORT: Joi.number().default(3306),
        DB_HOST: Joi.alternatives().try(
          Joi.string().ip(),
          Joi.string().domain(),
        ),
        DB_TYPE: Joi.string().valid('mysql', 'postgres'),
        DB_DATABASE: Joi.string().required(),
        DB_USERNAME: Joi.string().required(),
        DB_PASSWORD: Joi.string().required(),
        DB_SYNC: Joi.boolean().default(false),
        LOG_ON: Joi.boolean(),
        LOG_LEVEL: Joi.string(),
      }),
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService], // 想要获取配置，必须注入 ConfigService
      useFactory: (config: ConfigService) => {
        return {
          type: config.get(ConfigEnum.DB_TYPE),
          host: config.get(ConfigEnum.DB_HOST),
          port: config.get(ConfigEnum.DB_PORT),
          username: config.get(ConfigEnum.DB_USERNAME),
          password: config.get(ConfigEnum.DB_PASSWORD) as string,
          database: config.get(ConfigEnum.DB_DATABASE),
          entities: [User, Profile, Roles, Logs], // 插入实体文件，让TypeORM知道它的存在
          synchronize: config.get(ConfigEnum.DB_SYNC), // 同步本地模型到数据库，一般是初始化的时候去使用
          logging: ['error'],
        } as TypeOrmModuleOptions
      },
    }),
    UserModule,
  ],
  controllers: [AppController],
  providers: [AppService, Logger],

  // 导出 Logger，让其他模块可以使用，但是需要在模块中import，所以使用@Global()
  exports: [Logger],
})
export class AppModule {}
